package handle

import (
	"AcsGo/internal/domain"
	"AcsGo/internal/model"
	"strconv"
)

func HandleBookInfo(str string) (string, error) {
	queryRequest, err := domain.HandleBookInfoRequest(str)
	if err != nil {
		return "", err
	}
	lg.Debugf("queryRequest: %v", queryRequest)
	ci := "02"
	bkbm := queryRequest.ItemIdentifier.Value
	bkTitle := ""
	bkAuthor := ""
	isbn := ""
	price := ""
	kc := ""
	publish := ""
	subject := ""
	bn := ""
	pgNum := ""
	db, err := model.ConnectDB()
	if err != nil {
		return "", err
	}
	publicRecord, err := model.GetPbBookRecordBy(db, queryRequest.ItemIdentifier.Value)
	if err != nil {
		queryResponse := domain.InitBookInfoResponse(ci, bkbm, bkTitle, bkAuthor, isbn, price, kc, publish, subject, bn, pgNum)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("queryResponse: %v", sb)
		return sb, nil
	}
	bookid, _ := strconv.Atoi(publicRecord.BKRECD)

	book, err := model.GetBook(db, bookid)
	if err != nil {
		queryResponse := domain.InitBookInfoResponse(ci, bkbm, bkTitle, bkAuthor, isbn, price, kc, publish, subject, bn, pgNum)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("queryResponse: %v", sb)
		return sb, nil
	}
	if publicRecord.AutherBM.Valid {
		if publicRecord.AutherBM.String != "" {
			ci = "03"
		}
	} else {
		lg.Debugf("publicRecord.AutherBM.String +02: %v", publicRecord.AutherBM.String)
		ci = "02"
	}

	bkbm = publicRecord.BARBM
	bkTitle = book.Name
	bkAuthor = book.Author
	isbn = book.ISBN
	price = book.Price
	kc = book.IndxNb
	publish = book.PblcOrgnz
	subject = book.Name
	bn = book.TypeNb
	pgNum = book.Page
	queryResponse := domain.InitBookInfoResponse(ci, bkbm, bkTitle, bkAuthor, isbn, price, kc, publish, subject, bn, pgNum)
	sb, _ := queryResponse.StringFormat()
	lg.Debugf("success: %v", sb)
	return sb, nil
}
